package org.mule.robo;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Controller
{

    private String commandFile;
    private static final Pattern COMMAND_PATTERN = Pattern.compile("(\\w+)\\s(\\d+)\\s(\\w+)\\s(\\d+)");

    public Controller(String commandFile)
    {
        this.commandFile = commandFile;
    }

    private void run()
    {
        File file = new File("src/main/resources/" + commandFile);
        System.out.println("file.getAbsoluteFile(); = " + file.getAbsoluteFile());
        Scanner scanner = null;
        try
        {
            scanner = new Scanner(file);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        int size = scanner.nextInt();
        scanner.skip("\\s");
        List<Command> commands = new ArrayList<Command>();
        while (scanner.hasNextLine())
        {
            String line = scanner.nextLine();
            Matcher matcher = COMMAND_PATTERN.matcher(line);
            if (matcher.matches() && matcher.groupCount() == 4)
            {
                //TODO validate groups
                commands.add(CommandFactory.create(matcher));
            }
            else
            {
                if (!"quit".equals(line))
                {
                    throw new IllegalArgumentException("bad command: " + line);
                }
            }
        }

        Table table = new Table(size);
        table.run(commands);
    }

    public static void main(String[] args)
    {
        if (args.length != 1)
        {
            throw new IllegalArgumentException("Usage: Controller command-file");
        }
        new Controller(args[0]).run();
    }
}
